// A list of TimeInterval objects

module.exports = (function() {
  "use strict";

  var TimeInterval = require("../lib/timeInterval");


  // constructor
  function TimeIntervalList() {
    this.list = [];
  }

  TimeIntervalList.delimRE = /\s*[,;\uff1b]\s*/;
  TimeIntervalList.parse = function(text) {
    var hoursRanges = text.split(TimeIntervalList.delimRE);
    var list = new TimeIntervalList();

    for (var i in hoursRanges) {
      list.add(TimeInterval.parse(hoursRanges[i]));
    }

    return list;
  };

  TimeIntervalList.REsrc = "(?:" + TimeInterval.REsrc + ")(?:(?:" +
    TimeIntervalList.delimRE.source + ")(?:" + TimeInterval.REsrc + "))*";


  TimeIntervalList.prototype.add = function(timeInterval) {
    var n = this.list.length;
    var i = 0;
    while (i < n) {
      var curr = this.list[i];
      if (curr.overlaps(timeInterval)) {
        timeInterval = timeInterval.merge(curr);
        this.list.splice(i, 1);
        --n;
      } else {
        ++i;
      }
    }

    for (i=0; i<n; ++i) {
      var curr2 = this.list[i];
      if (timeInterval.start.smallerNotEqual(curr2.start)) {
        this.list.splice(i, 0, timeInterval);
        return;
      }
    }
    this.list.push(timeInterval);
  }

  TimeIntervalList.prototype.addList = function(that) {
    for (var i in that.list) {
      this.add(that.list[i]);
    }
  }

  TimeIntervalList.prototype.length = function() {
    return this.list.length;
  }

  TimeIntervalList.prototype.equals = function(that) {
    if (this === that) return true;
    if (!(that instanceof TimeIntervalList)) return false;
    var n = that.list.length;
    if (this.list.length !== n) return false;
    for (var i=0; i<n; ++i) {
      if (!this.list[i].equals(that.list[i]))
        return false;
    }
    return true;
  }

  TimeIntervalList.prototype.toString = function() {
    return this.list.join(",");
  }


  return TimeIntervalList;

}());

